<?php
class AdPostsController extends AppController {
	public $name       = 'AdPosts';
    public $components = array('Email');
    public $helpers    = array('Html', 'Form', 'Javascript');

    public function admin_index () {
        $this->pageTitle = __('Ads Listing', true);
        $this->set('adPosts', $this->paginate());
    } // admin_index

    public function admin_edit ($id) {
        if (empty($this->data)) {
            if (!$id) {
                $this->flash('<h4>'.__('Missing required id',true).'</h4>', 'index', 5);
            } else {
                $this->data = $this->AdPost->findById($id);
            }
        } else {
            if ($this->AdPost->save($this->data)) {
                $this->flash('<h4>'.__('The Post has been saved.',true).'</h4>', 'index');
            }
        }

        App::import('Model', 'User');
        $user = new User();
        $this->set('users', $user->find('list'));
    } // admin_edit

    public function admin_delete ($id) {
        if (!$id) {
            $this->set('pageTitle', __('Missing Post Id.',true));
            $this->flash('<h4>'.__('Missing Post Id.',true).'</h4>', '/admin/adPosts', 5);
            return false;
        } else if ($this->AdPost->deletePost($id)) {
            $this->Session->setFlash('<h4>'.__('Post deleted',true).'</h4>', 'default', array('class'=>'boxSuccess'));
            $this->redirect('/admin/adPosts');
        }
    } // admin_delete

    public function myAds () {
        $myid = $this->Session->read('Auth.User.id');

        if (!$myid) {
            $message = __('The page you tried to access is restricted. You have been redirected to the page below.', true);
            $this->Session->setFlash('<h4>'.$message.'</h4>', 'default', array('class'=>'boxError'));
            $this->redirect('/users/login');
        }

        $this->pageTitle = __('My Ads', true);
        $this->set('adPosts', $this->paginate('AdPost', 'user_id='.$myid));
    } // myAds

    public function index () {
        $this->helpers = array('Text', 'Time');

        $fields = array(
            'AdPost.id', 'AdPost.type', 'AdPost.title', 'AdPost.description', 'AdPost.currency', 'AdPost.price',
            'AdPost.location', 'AdPost.created', 'AdCategory.id','AdCategory.category','DefaultImage.filename'
        );
        $params = array(
            'recursive'  => 0,
            'conditions' => array('AdPost.active' => 1),
            'fields'     => $fields,
            'order'      => 'AdPost.created DESC',
            'limit'      => 5
        );
        $this->paginate = $params;
        $this->set('adPosts', $this->paginate());
    } // index

    public function browse ($id) {
$this->helpers = array('Html', 'Form', 'Javascript', 'Text', 'Time');

        if (!class_exists('File')) {
            uses('file');
        }

        $lines = file(VIEWS.$this->viewPath.DS.$this->action.$this->ext);
        $copy  = $tpl = false;
        foreach ($lines as $line) {
            if ($copy) {
                if (strpos($line, '</tbody>')) {
                    break;
                }
                $tpl .= trim(str_replace("'", "\\'", $line));
            } else if (!$copy && strpos($line, '<tbody class="template')) {
                $copy = true;
            }
        }
        $this->set('template', $tpl);

        $fields = array(
            'AdPost.id', 'AdPost.type', 'AdPost.title', 'AdPost.description', 'AdPost.currency', 'AdPost.price',
            'AdPost.location', 'AdPost.created', 'AdCategory.id','AdCategory.category','DefaultImage.filename'
        );
        $params = array(
            'recursive' => 0,
            'fields'    => $fields,
            'order'     => 'AdPost.created DESC',
            'limit'     => 5
        );

        if ($id && $id != 'all') {
            $params['conditions'] = array('AdPost.ad_category_id' => $id);
        } else {
            $id = '';
        }

        App::import('Model', 'AdCategory');
        $category = new AdCategory();
        $adPost = $category->find('first', array('conditions'=>'id='.$id, 'fields'=>array('parent','category')));
        $this->set('adPost', $adPost);

        //$this->paginate = $params;
        //$this->set('adPosts', $this->paginate());
        $this->pageTitle = __($adPost['AdCategory']['parent'],true).' - '.__($adPost['AdCategory']['category'],true);
        $this->set('catId', $id);
    } // browse

    public function quickSearch ($group, $keywords) {
$this->helpers = array('Html', 'Form', 'Javascript', 'Text', 'Time');
        $parent = array(
            'AdCategory' => array(
                'parent' => $group
            )
        );

        if (!class_exists('File')) {
            uses('file');
        }

        $lines = file(VIEWS.$this->viewPath.DS.'browse'.$this->ext);
        $copy  = $tpl = false;
        foreach ($lines as $line) {
            if ($copy) {
                if (strpos($line, '</tbody>')) {
                    break;
                }
                $tpl .= trim(str_replace("'", "\\'", $line));
            } else if (!$copy && strpos($line, '<tbody class="template')) {
                $copy = true;
            }
        }
        $this->set('template', $tpl);
        $this->set('adPost', $parent);
        $this->set('group', $group);
        $this->set('keywords', $keywords);

        $this->pageTitle = __($group,true).' - '.__(ucwords($keywords),true);
        $this->render('browse');
    } // quickSearch

    public function axSearch () {
//sleep(1);
        Configure::write('debug', 0);
        $search = $json = array();
        $status = 1;
        $fields = array(
            'AdPost.id', 'AdPost.type', 'AdPost.title', 'AdPost.description', 'AdPost.currency', 'AdPost.price',
            'AdPost.location', 'AdPost.created', 'AdCategory.id','AdCategory.category','DefaultImage.filename'
        );
        $params = array(
            'recursive' => 0,
            'fields'    => $fields,
            'order'     => 'AdPost.created DESC',
            'limit'     => 10
        );

        extract($_POST);
        if ($catId) {
            $search = array(
                'AdPost.ad_category_id' => $catId,
                'AdPost.active' => 1
            );
        }
        if ($page) {
            $params['page'] = $page;
        }
        if ($minPrice && $maxPrice) {
            if ($minPrice > $maxPrice) {
                $tmp      = $minPrice;
                $maxPrice = $minPrice;
                $minPrice = $tmp;
            }
        }
        if ($minPrice) {
            $search[] = array('AdPost.price >=' => $minPrice);
        }
        if ($maxPrice) {
            $search[] = array('AdPost.price <=' => $maxPrice);
        }
        if ($condition && $condition != 'all') {
            $search[] = array('AdPost.condition' => $condition);
        }
        if ($type && $type != 'all') {
            $search[] = array('AdPost.type' => $type);
        }
        if ($group && low($group) != 'all') {
            $search[] = array('AdCategory.parent' => $group);
        }
        if ($keywords) {
            $search[] = array(
                'OR' => array(
                    'AdPost.title LIKE'       => '%'.$keywords.'%',
                    'AdPost.description LIKE' => '%'.$keywords.'%'
                )
            );
        }
        if ($location) {
            $search[] = array('AdPost.location' => $location);
        }
        if (Configure::read('site.filterLocation') && $this->userLocationId) {
            $search[] = array('AdPost.location_id' => $this->userLocationId);
        }

        if ($newSearch) { // new search need to find count
            $json['total']      = $this->AdPost->find('count', array('conditions'=>$search));
            $json['limit']      = $params['limit'];
            $json['counterTpl'] = __('Showing #{start} - #{end} of #{total} ads', true);
        }
        $params['conditions'] = $search;

        if ($newSearch && $json['total'] == 0) {
            $status = 0;
            $json   = array('total'=>0);
        } else {
            App::import('Helper', 'Text');
            App::import('Helper', 'Time');
            $text = new TextHelper();
            $time = new TimeHelper();
            $zone = Configure::read('user.timezone');

            foreach ($this->AdPost->find('all', $params) as $i=>$v) {
                $rs = $v['AdPost'];

                $rs['type']  = ($rs['type'] == 'W') ? __('Wanted:',true) : '';
                $rs['price'] = ($rs['price'] == '0.00') ? '' : $rs['price'];
                //$rs['category'] = $v['AdCategory']['category'];
                $rs['image'] = ($v['DefaultImage']['filename']) ? 's_'.$v['DefaultImage']['filename'] : '';

                if (strlen($rs['description']) > 100) {
                    $rs['description'] = $text->truncate($rs['description']);
                }

                $rs['time'] = $time->format('g:ia', $rs['created'], false, $zone);
                if ($time->isToday($rs['created'])) {
                    $rs['time']    = '&lt; '.$time->timeAgoInWords($rs['created']);
                    $rs['created'] = __('Today', true);
                } else if ($time->wasYesterday($rs['created'])) {
                    $rs['created'] = __('Yesterday', true);
                } else {
                    $rs['created'] = $time->format('l, F j, Y', $rs['created'], false, $zone);
                }

                $json['data'][$i] = $rs;
            }

            $json['adsPath'] = $this->base.'/adPosts/view/';
            $json['imgPath'] = $this->base.'/img/images/';
        }

        header('X-JSON: { status:'.$status.' }');
        $this->set('json', $json);
        $this->render(false, 'json');
    } // axSearch

    public function add ($id) {
        if (empty($id)) {
            $this->components = array('Session');
            $this->Session->setFlash('<h4>'.__('Select a category before adding new post',true).'</h4>', 'default', array('class'=>'boxAtt'));
            $this->redirect('/adCategories/selectCategory');
        }

        $this->pageTitle = __('Ad Details', true);
        $this->data['User']['email'] = $this->Cookie->read('User.email');
//$this->Cookie->Destroy();
//$this->Session->del('Upload');
//pr($this->Session->read('Upload'));
        App::import('Model', 'AdCategory');
        $adCategory = new AdCategory();
        $category   = $adCategory->findById($id);

        $this->javascripts = am($this->javascripts, 'webtoolkit.aim');
        $this->set('pageTitle', __('Create Your Ad', true));
        $this->set('selectedCategory', $category['AdCategory']['parent'].' > '.$category['AdCategory']['category']);
        $this->set('ad_category_id', $id);
        $this->set('buttonLabel', __('Post Your Ad',true));
    } // add

    public function axAdd () {
        Configure::write('debug', 0);
        $this->AdPost->set($this->data);
        $model = 'AdPost';
        $stt   = -1;

        //TODO// user session 1st
        $user = $this->Cookie->read('User');
        if (!$user['email']) { // this is first time poster
            $user = $this->__addNewAccount(); // open member account
        } else {
            $user['status'] = true;
        }

        $valid = $this->AdPost->validates(); // check if post values valid

        if ($valid && $user['id']) {
            $this->data['AdPost']['location_id'] = $this->Cookie->read('User.locationId');
            $this->data['AdPost']['user_id']     = $user['id'];

            if ($this->AdPost->save($this->data)) {
                $stt  = 1;
                $id   = $this->AdPost->id;
                $json = array(
                    'id'      => $id,
                    'message' => __('New post saved.', true)
                );

                $image_id = $this->_saveImages($id);
                if ($image_id) { // save default image
                    $this->AdPost->saveField('ad_image_id', $image_id);
                }

                // send email
                $this->_sendManagePostMail($user['email'], $this->data['AdPost']['title'], $id);
            }
        } else {
            if ($user['status'] == false) { // fail open new member account
                if (is_array($user['errors'])) {
                    $json['error'] = $user['errors'];
                } else {
                    $json['message'] = __('Fail opening account for the new post', true);
                }
            }
            if (!$valid) { // invalid post
                foreach ($this->AdPost->invalidFields() as $k=>$v) {
                    $json['error'][] = array('id'=>$model.ucwords($k), 'field'=>$k, 'code'=>$v);
                }
            }
        }

        header('X-JSON: { status:'.$stt.' }');
        $this->set('json', $json);
        $this->render(false, 'json');
    } // axAdd

    public function edit ($id=null, $code=null) {
        $b = $this->_managePermission($id, $code); // check if has permission edit

        $this->javascripts = am($this->javascripts, 'webtoolkit.aim');
        $this->pageTitle = __('Edit Posting', true);
        $this->set('pageTitle', __('Edit Posting', true));

        $this->data = $this->AdPost->findById($id);

        $this->set('selectedCategory', $this->data['AdCategory']['parent'].' > '.$this->data['AdCategory']['category']);
        $this->set('ad_category_id', $this->data['AdPost']['ad_category_id']);
        $this->set('buttonLabel', __('Make Changes',true));

        if ($b) {
            $this->render('add');
        }
    } // edit

    public function axEdit () {
        Configure::write('debug', 0);
        $this->AdPost->set($this->data);
        $model = 'AdPost';
        $id    = $this->data['AdPost']['id'];
        $stt   = -1;

        $valid = $this->AdPost->validates(); // check if post values valid

        if ($valid) {
            if ($this->AdPost->save($this->data)) {
                $stt  = 1;
                $json = array(
                    'post_id' => $id,
                    'message' => __('Your post updated.', true)
                );

                $image_id = $this->_saveImages($id); // any new images uploaded
                if ($image_id) { // replace post default image if empty
                    $this->AdPost->saveDefaultImage($id, $image_id);
                }
            } else {
                $json = array('message' => __('Fail saving posting at this time.', true));
            }
        } else {
            foreach ($this->AdPost->invalidFields() as $k=>$v) {
                $json['error'][] = array('id'=>$model.ucwords($k), 'field'=>$k, 'code'=>$v);
            }
        }

        header('X-JSON: { status:'.$stt.' }');
        $this->set('json', $json);
        $this->render(false, 'json');
    } // axEdit

    public function delete ($id=null, $code=null) {
        $b = $this->_managePermission($id, $code); // check if has permission delete the posting

        $sitename = Configure::read('site.sitename');
        $sitename = __($sitename, true);
        $title    = $this->AdPost->field('title', 'id='.$id);
        $message  = __('Your posting "%title%" with id: %id% has been deleted. Thanks for using %sitename%', true);
        $message  = r(array('%title%','%id%','%sitename%'), array($title, $id, $sitename), $message);

        $this->AdPost->deletePost($id);
        $this->flash($message, '/', 5);
    } // delete

    public function publish ($id=null, $code=null) {
        $b = $this->_managePermission($id, $code); // check if has permission publish the posting

        $this->AdPost->id = $id;
        $this->AdPost->saveField('active', 1);
        $this->redirect('/adPosts/view/'.$id.'/'.$code);
    } // publish

    public function unpublish ($id=null, $code=null) {
        $b = $this->_managePermission($id, $code); // check if has permission unpublish the posting

        $this->AdPost->id = $id;
        $this->AdPost->saveField('active', 0);
        $this->redirect('/adPosts/view/'.$id.'/'.$code);
    } // unpublish

    public function view ($id=null, $code=null) {
        $b = $this->_managePermission($id, $code, 'view'); // check if has permission manage posting

        if ($code) {
            $this->set('geturl', $id.'/'.$code);
        } else {
            $this->set('geturl', $id);
        }

        $adPost = $this->AdPost->findById($id);
        $visits = $adPost['AdPost']['visit'] + 1;

        $this->helpers = am($this->helpers, array('Time'));
        $this->AdPost->id = $id;
        $this->AdPost->saveField('visit', $visits);
        $this->pageTitle = $adPost['AdPost']['title'].' - '.__($adPost['AdCategory']['parent'],true) .
                           ' - '.__($adPost['AdCategory']['category'],true);
        $this->set('id', $id);
        $this->set('code', $code);
        $this->set('zone', Configure::read('user.timezone'));
        //$this->set('neighbors', $this->AdPost->find('neighbors', array('field'=>'AdPost.id', 'value'=>$id, 'recursive'=>-1, 'fields'=>'id')));
        $this->set('adPost', $adPost);
    } // view


    private function __addNewAccount () {
        App::import('Vendor', 'functions');
        App::import('Model', 'User');
        $email = low($this->data['User']['email']);
        $user  = new User();
        $info  = $user->findByEmail($email, array('fields'=>'User.id'));
        $rs    = array('status'=>false);

        if ($info['User']['id']) { // email exists, retrieve account id from database
            $id = $info['User']['id'];
            $rs = array('status'=>true, 'id'=>$id, 'new'=>false);
            $this->Cookie->write('User.id', $id, true, '1 year');
            $this->Cookie->write('User.email', $email, true, '1 year');
        } else { // create new account
            $this->data['User']['email']    = $email;
            $this->data['User']['password'] = f_randomCode(); //$this->Auth->password(f_randomCode());
            $this->data['User']['active']   = 0;
            $user->set($this->data);

            if ($user->validates()) { // data valid
                if ($user->save($this->data)) {
                    $id = $user->id;
                    $rs = array('status'=>true, 'id'=>$id, 'new'=>false);
                    $this->Cookie->write('User.id', $id, true, '1 year');
                    $this->Cookie->write('User.email', $email, true, '1 year');
                }
            } else {
                $err = $user->invalidFields();
                foreach ($err as $k=>$v) {
                    $errors[] = array('id'=>'User'.ucwords($k), 'field'=>$k, 'code'=>$v);
                }
                $rs['errors'] = $errors;
            }
        }

        return $rs;
    } // __addNewAccount

    private function _sendManagePostMail ($email, $title, $id) {
        $sitename = Configure::read('site.sitename');
        $sitename = __($sitename, true);
        $delivery = (Configure::read('debug') > 1) ? 'debug' : 'mail';

        $this->Email->to       = $email;
        $this->Email->replyTo  = 'noreply@'.env('HTTP_HOST');
        $this->Email->from     = $sitename.' <noreply@'.env('HTTP_HOST').'>';
        $this->Email->subject  = 'POST/EDIT/DELETE : '.$title;
        $this->Email->template = 'manage_post';
        $this->Email->sendAs   = 'both';
        $this->Email->delivery = $delivery;

        $secret = Configure::read('Security.salt');
        $code   = md5($id.$secret);
        $data   = array(
            'url'      => Router::url('/adPosts/view/'.$id.'/'.$code, true),
            'sitename' => $sitename
        );

        $this->set($data);
        $this->Email->send();
    } // _sendManagePostMail

    private function _saveImages ($id) {
        if (!$this->Session->Check('Upload')) {
            return 0;
        }

        $upload  = $this->Session->read('Upload');
        $tmpPath = WWW_ROOT.'img'.DS.'tmp'.DS;
        $imgPath = WWW_ROOT.'img'.DS.'images'.DS;
        $data    = array();

        foreach ($upload as $imgInfo) {
            $data[] = am(array('ad_post_id'=>$id), $imgInfo);
        }

        App::import('Model', 'AdImage');
        $image = new AdImage();

        $image->set($data);
        if (!$image->validates()) { // data invalid
            return false;
        }
        if (!$image->saveAll($data)) {
            return false;
        }
        $id = $image->field('id', '`ad_post_id`='.$id, 'id'); // retrieve one inserted image id

        foreach ($upload as $imgInfo) {
            @rename($tmpPath.$imgInfo['filename'], $imgPath.$imgInfo['filename']);
            @rename($tmpPath.'s_'.$imgInfo['filename'], $imgPath.'s_'.$imgInfo['filename']);
        }

        $this->Session->del('Upload');
        return $id;
    } // _saveImages

    private function _managePermission ($id=null, $code=null, $action=null) {
        if (!$id) {
            $this->set('pageTitle', __('Missing Post Id.',true));
            $this->flash('<h4>'.__('Missing Post Id.',true).'</h4>', '/', 8);
            return false;
        }
        if ($code) { // manage without login session
            $secret = Configure::read('Security.salt');
            $check  = md5($id.$secret);

            if ($check == $code) {
                $this->set('manage', true);
                return true;
            }

            $this->set('pageTitle', __('Invalid manage code',true));
            $this->flash('<h4>'.__('Invalid manage code',true).'</h4>', '/', 5);
            return false;
        }

        // check if user has the right to manage
        if (!$myid = $this->Session->read('Auth.User.id')) { // has not logged, redirect user to login screen
            if ($action == 'view') {
                return false;
            }

            $message = __('The page you tried to access is restricted. You have been redirected to the page below.', true);
            $this->Session->setFlash('<h4>'.$message.'</h4>', 'default', array('class'=>'boxAtt'));
            $this->Session->write('Auth.redirect', '/adPosts/'.$this->params['action'].'/'.$id);
            $this->redirect('/users/login');
            return false;
        }

        $userId = $this->AdPost->field('user_id', 'AdPost.id='.$id);
        if ($userId != $myid) { // not the post owner
            $message = __('You has no right to manage this post.', true);

            if ($action != 'view') {
                $this->Session->setFlash('<h4>'.$message.'</h4>', 'default', array('class'=>'boxError'));
                $this->redirect('/adPosts/view/'.$id);
            }
            return false;
        } else if ($userId == $myid) {
            $this->set('manage', true);
        }

        if ($code) {
            $this->set('manage', true);
        }
        return true;
    } // _managePermission

} // AdPostsController
?>